<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small">筛选</el-button>
            <el-button type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" border stripe>
        <el-table-column label="文章标题" prop="title">
          <!-- 如果希望自定义数据的渲染方式推荐使用作用域插槽 -->
          <template v-slot="{ row }">
            <!-- 把标题渲染成文字链接 -->
            <el-link type="primary" @click="showDetail(row.id)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{ row }">
            {{ row.pub_date | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage2"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="100"
        layout="sizes, prev, pager, next"
        :total="1000"
      >
      </el-pagination>
    </el-card>

    <!-- 发表文章的对话框 -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubVisible"
      fullscreen
      :before-close="handleClose"
      @closed="onDialogClosed"
    >
      <!-- 发表文章的表单 -->
      <el-form :model="pubForm" label-width="80px" :rules="pubFormRules" ref="pubFormRef">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" style="width: 100%" placeholder="请选择分类">
            <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 文章的内容 -->
        <el-form-item label="文章内容">
          <!-- 使用富文本编译器 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img :src="imgURL" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none" accept="image/*" ref="iptFileRef" @change="onFileChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="onPub('已发布')">发布</el-button>
          <el-button type="info" @click="onPub('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 文章详情对话框 -->
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 文章的封面 -->
      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import { getCateListAPI, pubArticleAPI, getArtListAPI, getArticleAPI, deleteArticle } from '@/api/article.js'
import defaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  created() {
    this.initCateList()
    this.initArtList()
  },
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubVisible: false,
      // 发表文章的表单数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: null
      },
      pubFormRules: {
        title: [
          { required: true, message: '文章标题是必填项', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在1到30个字符之间', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '文章分类是必选项', trigger: 'change' }]
      },
      // 文章分类
      cateList: [],
      // 图片封面的URL地址
      imgURL: defaultImg,
      artList: [],
      total: 0,
      artDetail: {},
      detailVisible: false
    }
  },
  methods: {
    // 监听对话框即将关闭的行为
    // 形参中的done是个函数，两种调用方式
    // done() 表示关闭对话框
    // done(false) 表示阻止关闭对话框
    async handleClose(done) {
      // 1、弹框询问用户是否真的要关闭对话框
      // 2、如果用户取消了关闭
      // 3、如果用户确定了关闭
      const result = await this.$confirm('此操作会导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') {
        done(false)
      } else {
        done()
      }
    },
    async initCateList() {
      const { data: res } = await getCateListAPI()
      if (res.code !== 0) return
      this.cateList = res.data
    },
    onFileChange(e) {
      const arr = e.target.files
      if (arr.length === 0) {
        this.pubForm.cover_img = null
        this.imgURL = defaultImg
      } else {
        this.pubForm.cover_img = arr[0]
        this.imgURL = URL.createObjectURL(arr[0])
      }
    },
    // 点击按钮即将发表文章
    onPub(state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(valid => {
        if (!valid) return
        // 判断用户是否选择了封面
        if (this.pubForm.cover_img === null) return this.$message.error('必须选择文章封面')
        if (!this.pubForm.content) return this.$message.error('文章内容不能为空')
        this.postArticle()
      })
    },
    async postArticle() {
      // 把this.pubForm对象，转换成FormData格式的数据对象
      // 调用发表文章的API接口,把步骤1得到的FormData对象,发送给接口
      // 判断发表文章是否成功
      // 如果发表失败则提示对象
      // 如果发表成功,则提示对象关闭对话框刷新文章列表的数据
      const fd = new FormData()
      Object.keys(this.pubForm).forEach(k => {
        fd.append(k, this.pubForm[k])
      })
      const { data: res } = await pubArticleAPI(fd)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.pubVisible = false
    },
    // 监听对话框关闭事件
    onDialogClosed() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.state = ''
      this.pubForm.cover_img = null
      this.imgURL = defaultImg
      this.$refs.iptFileRef.values = ''
    },
    async initArtList() {
      const { data: res } = await getArtListAPI(this.q)
      if (res.code !== 0) return this.$message.error('获取文章列表数据失败')
      this.artList = res.data
      this.total = res.total
    },
    // 点击链接展示文章详情
    async showDetail(id) {
      // 1、封装接口
      const { data: res } = await getArticleAPI(id)
      if (res.code !== 0) return this.$message.error(res.message)
      this.artDetail = res.data
      this.detailVisible = true
    },
    async remove(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return
      const { data: res } = await deleteArticle(id)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.initArtList()
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}

// 解决元素对齐问题
/deep/ .ql-snow .ql-picker-label::before {
  position: relative;
  top: -8px;
}

// 解决元素对齐问题
/deep/ .ql-picker-label > svg {
  position: relative;
  top: -6px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
